package com.pig4cloud.pig.admin.task;

import com.pig4cloud.pig.admin.api.entity.NewsList;
import com.pig4cloud.pig.admin.constant.CommonConstant;
import com.pig4cloud.pig.admin.task.base.BaseTask;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

@Component
public class JrrdNews extends BaseTask {


	@Override
	@Scheduled(cron = "0 0/5 * * * ?")
	public void doTask() {
		String html = httpUtilService.getRequest(1,JrrdNews.class,"https://tophub.today/n/DpQvNABoNE", CommonConstant.UTF8);
		Document parse = Jsoup.parse(html);
		Elements tobody = parse.select("#page > div.c-d.c-d-e > div.Zd-p-Sc > div:nth-child(1) > div.cc-dc-c > div > div.jc-c > table > tbody");
		Elements trs = tobody.get(0).select("tr");
		for(Element tr : trs) {
			String topic = tr.select("td.al > a").text();
			String topicUrlString = null;
			try {
				topicUrlString = new String(java.net.URLEncoder.encode(topic,"utf-8").getBytes());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String link = "https://www.douyin.com/search/"+topicUrlString+"";
			String original_weight = tr.select("td:nth-child(3)").text();
			//热度值去除中文
			original_weight = original_weight.replaceAll("[\u4e00-\u9fa5]","");
			if (original_weight.contains(".")){
				BigDecimal bigDecimal = new BigDecimal(original_weight);
				original_weight = bigDecimal.multiply(new BigDecimal("10000")).intValue() + "";
			}
			if(topic==null) {
				System.out.println("### topic is null");
				continue;
			}
			NewsList commonData = NewsList.create(idGenerator.nextId());
			commonData.setTitle(topic);
			commonData.setUrl(link);
			commonData.setCategory("今日热点汇总");
			commonData.setCreateTime(CommonConstant.getDay());
			pushNewsToRedis(commonData);
		}
	}
}
